package org.jeecg.modules.asset.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.ImportExcelUtil;
import org.jeecg.modules.asset.entity.AssetMessage;
import org.jeecg.modules.asset.entity.AssetMessageChange;
import org.jeecg.modules.asset.service.IAssetMessageChangeService;
import org.jeecg.modules.asset.service.IAssetMessageService;
import org.jeecg.modules.asset.vo.EquipmentAssetEntity;
import org.jeecg.modules.asset.vo.EquipmentAssetVO;
import org.jeecg.modules.asset.vo.SpaceAssetEntity;
import org.jeecg.modules.system.entity.SysPermission;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysPermissionService;
import org.jeecg.modules.system.util.ChangeLogUtil;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

 /**
 * @Description: 资产台账
 * @Author: jeecg-boot
 * @Date:   2025-11-14
 * @Version: V1.0
 */
@Api(tags="资产台账")
@RestController
@RequestMapping("/asset/assetMessage")
@Slf4j
public class AssetMessageController extends JeecgController<AssetMessage, IAssetMessageService> {
	@Autowired
	private IAssetMessageService assetMessageService;
	 @Autowired
	 private ISysDictService sysDictService;
	 @Autowired
	 private IAssetMessageChangeService assetMessageChangeService;
	 @Autowired
	 private ISysPermissionService sysPermissionService;

	/**
	 * 分页列表查询
	 *
	 * @param assetMessage
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "资产台账-分页列表查询")
	@ApiOperation(value="资产台账-分页列表查询", notes="资产台账-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<AssetMessage>> queryPageList(AssetMessage assetMessage,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		List<SysPermission> sysPermissions = sysPermissionService.queryByUser(sysUser.getUsername());
		int size = sysPermissions.stream().filter(sysPermission -> StringUtils.isNotBlank(sysPermission.getPerms()) &&
				sysPermission.getPerms().contains("assetMessage:isVisible")).collect(Collectors.toList()).size();
		if(size == 0){
			assetMessage.setIsVisible("1");
		}
		QueryWrapper<AssetMessage> queryWrapper = QueryGenerator.initQueryWrapper(assetMessage, req.getParameterMap());
		Page<AssetMessage> page = new Page<AssetMessage>(pageNo, pageSize);
		IPage<AssetMessage> pageList = assetMessageService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @GetMapping(value = "/listAll")
	 public Result<IPage<AssetMessage>> queryAllPageList(AssetMessage assetMessage,
													  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													  HttpServletRequest req) {
		 QueryWrapper<AssetMessage> queryWrapper = QueryGenerator.initQueryWrapper(assetMessage, req.getParameterMap());
		 Page<AssetMessage> page = new Page<AssetMessage>(pageNo, pageSize);
		 IPage<AssetMessage> pageList = assetMessageService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	 /**
	  * 获取空间资产下，设备资产，存放位置为null
	  */
	 @GetMapping(value = "/listByPlace")
	 public Result<List<AssetMessage>> listByPlace(AssetMessage assetMessage) {
		 QueryWrapper<AssetMessage> queryWrapper = new QueryWrapper<AssetMessage>();
		 queryWrapper.eq("belong_space_code", assetMessage.getId());
		 queryWrapper.and(queryWrapper1 -> queryWrapper1.isNull("place").or().eq("place", ""));
		 List<AssetMessage> list = assetMessageService.list(queryWrapper);
		 return Result.OK(list);
	 }


	 @GetMapping(value = "/getByContractId")
	 public Result<IPage<AssetMessage>> queryAllPageList(@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														 HttpServletRequest req) {
		 String ids = req.getParameter("ids");
		 QueryWrapper<AssetMessage> queryWrapper = new QueryWrapper<>();
		 queryWrapper.in("id", ids.split( ","));
		 Page<AssetMessage> page = new Page<AssetMessage>(pageNo, pageSize);
		 IPage<AssetMessage> pageList = assetMessageService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }
	
	/**
	 *   添加
	 *
	 * @param assetMessage
	 * @return
	 */
	@AutoLog(value = "资产台账-添加")
	@ApiOperation(value="资产台账-添加", notes="资产台账-添加")
	//@RequiresPermissions("org.jeecg.modules:asset_message:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody AssetMessage assetMessage) {
		String assetCode = getAssetCode(assetMessage);
		assetMessage.setAssetCode(assetCode);
		assetMessageService.save(assetMessage);
		return Result.OK("资产创建成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param assetMessage
	 * @return
	 */
	@AutoLog(value = "资产台账-编辑")
	@ApiOperation(value="资产台账-编辑", notes="资产台账-编辑")
	//@RequiresPermissions("org.jeecg.modules:asset_message:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	@Transactional
	public Result<String> edit(@RequestBody AssetMessage assetMessage) {
		AssetMessage oldAsset = assetMessageService.getById(assetMessage.getId());
		assetMessageService.updateById(assetMessage);
		// 记录变更
		List<AssetMessageChange> changes = ChangeLogUtil.compareChanges(oldAsset, assetMessage, assetMessage.getId());
		assetMessageChangeService.saveBatch(changes);

		//通过空间资产修改设备资产存放位置
		if("1".equals(assetMessage.getType())){
			List<EquipmentAssetVO> equipmentList = assetMessage.getEquipmentList();
			for (EquipmentAssetVO equipment : equipmentList) {
				if (StringUtils.isNotBlank(equipment.getPlace())){
					AssetMessage equipmentAsset = assetMessageService.getById(equipment.getId());
					//变更记录
					AssetMessageChange change = new AssetMessageChange();
					change.setChangeField("place");
					change.setChangeFieldName("存放位置");
					change.setOldValue(equipmentAsset.getPlace());
					change.setNewValue(equipment.getPlace());
					change.setPid(equipment.getId());
					assetMessageChangeService.save(change);

					equipmentAsset.setPlace(equipment.getPlace());
					assetMessageService.updateById(equipmentAsset);
				}
			}
		}
		return Result.OK("资产编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "资产台账-通过id删除")
	@ApiOperation(value="资产台账-通过id删除", notes="资产台账-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:asset_message:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		AssetMessage assetMessage = assetMessageService.getById(id);
		if("1".equals(assetMessage.getType())){
			long count = assetMessageService.count(new QueryWrapper<AssetMessage>().eq("belong_space_code", assetMessage.getId()));
			if(count>0){
				return Result.error("无法删除，请先处理该空间下的所有关联设备");
			}
		}
		assetMessageService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "资产台账-批量删除")
	@ApiOperation(value="资产台账-批量删除", notes="资产台账-批量删除")
	//@RequiresPermissions("org.jeecg.modules:asset_message:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.assetMessageService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "资产台账-通过id查询")
	@ApiOperation(value="资产台账-通过id查询", notes="资产台账-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<AssetMessage> queryById(@RequestParam(name="id",required=true) String id) {
		AssetMessage assetMessage = assetMessageService.getById(id);
		if(assetMessage==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(assetMessage);
	}

	 /**
	  * 导出excel
	  *
	  * @param request
	  * @param assetMessage
	  */
	 //@RequiresPermissions("org.jeecg.modules:asset_message:exportXls")
	 @RequestMapping(value = "/exportXls")
	 public void exportXls(HttpServletRequest request,HttpServletResponse response, AssetMessage assetMessage)  {
		 QueryWrapper<AssetMessage> queryWrapper = QueryGenerator.initQueryWrapper(assetMessage, request.getParameterMap());
		 List<AssetMessage> exportList = assetMessageService.list(queryWrapper);
		 //多个sheet
		 List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
		 try {
			 // 空间资产
			 Map<String, Object> map = new HashMap<String, Object>();
			 map.put("title",getExportParams("空间资产台账"));//表格title
			 map.put("entity", SpaceAssetEntity.class);//表格对应实体
			 List<AssetMessage> spaceAssetList = exportList.stream().filter(item -> item.getType().equals("1")).collect(Collectors.toList());
			 List<SpaceAssetEntity> spaceAssetEntityList = new ArrayList<>();
			 for (AssetMessage message : spaceAssetList) {
				 SpaceAssetEntity spaceAssetEntity = new SpaceAssetEntity();
				 BeanUtils.copyProperties(message, spaceAssetEntity);
				 spaceAssetEntityList.add(spaceAssetEntity);
			 }
			 map.put("data", spaceAssetEntityList);
			 listMap.add(map);

			 // 设备资产
			 Map<String, Object> map2 = new HashMap<String, Object>();
			 map2.put("title",getExportParams("设备资产台账"));//表格title
			 map2.put("entity", EquipmentAssetEntity.class);//表格对应实体
			 List<AssetMessage> equipmentAssetList = exportList.stream().filter(item -> item.getType().equals("2")).collect(Collectors.toList());
			 List<EquipmentAssetEntity> equipmentAssetEntityList = new ArrayList<>();
			 for (AssetMessage message : equipmentAssetList) {
				 EquipmentAssetEntity equipmentAssetEntity = new EquipmentAssetEntity();
				 BeanUtils.copyProperties(message, equipmentAssetEntity);
				 equipmentAssetEntityList.add(equipmentAssetEntity);
			 }
			 map2.put("data", equipmentAssetEntityList);
			 listMap.add(map2);

			 Workbook workbook = ExcelExportUtil.exportExcel(listMap,ExcelType.XSSF);
			 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			 response.setHeader("Content-Disposition", "attachment; filename=\"asset_data.xlsx\"");
			 workbook.write(response.getOutputStream());
			 workbook.close();
		 } catch (Exception e) {
			 log.error("导出Excel文件失败", e);
			 e.printStackTrace();
		 }
	 }

	 //导出参数
	 public static ExportParams getExportParams(String name) {
		 //表格名称,sheet名称,导出版本
		 return  new ExportParams(name,name, ExcelType.XSSF);
	 }

	 /**
	  * 通过excel导入数据
	  *
	  * @param request
	  * @param
	  * @return
	  */
	 //@RequiresRoles({"admin"})
	 @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	 public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		 // 资产分类
		 List<DictModel> assetCodeList = sysDictService.getDictItems("asset_all_code");
		 String assetAllCode = assetCodeList.stream().map(item -> item.getValue()).collect(Collectors.joining(","));
         // 所属资产 项目码
		 List<DictModel> belongAssetList = sysDictService.getDictItems("belong_asset");
		 String  belongAsset = belongAssetList.stream().map(item -> item.getValue()).collect(Collectors.joining(","));
         // 所属公司
		 List<DictModel> assetCompanyList = sysDictService.getDictItems("asset_company");
		 String  assetCompany = assetCompanyList.stream().map(item -> item.getValue()).collect(Collectors.joining(","));

		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 int successLines = 0, errorLines = 0;
		 int equiSuccessLines = 0, equiErrorLines = 0;
		 List<String> errorMessage = new ArrayList<>();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(1);
			 params.setHeadRows(2);
			 params.setNeedSave(true);
			 try {
				 params.setSheetNum(1);
				 List<SpaceAssetEntity> list1 = ExcelImportUtil.importExcel(file.getInputStream(), SpaceAssetEntity.class, params);
				 params.setSheetNum(2);
				 List<EquipmentAssetEntity> list2 = ExcelImportUtil.importExcel(file.getInputStream(), EquipmentAssetEntity.class, params);
				 for (int i = 0; i < list1.size(); i++) {
					 SpaceAssetEntity spaceAssetEntity = list1.get(i);
					 if (StringUtils.isBlank(spaceAssetEntity.getAssetName())){
						 errorLines++;
						 errorMessage.add("空间资产，第 " + (i+4) + " 行，资产名称不能为空，忽略导入。");
						 continue;
					 }
					 if (StringUtils.isBlank(spaceAssetEntity.getSpaceType())){
						 errorLines++;
						 errorMessage.add("空间资产，第 " + (i+4) + " 行，空间类型不能为空，忽略导入。");
						 continue;
					 }
					 if (StringUtils.isBlank(spaceAssetEntity.getBelongAsset())){
						 errorLines++;
						 errorMessage.add("空间资产，第 " + (i+4) + " 行，所属资产不能为空，忽略导入。");
						 continue;
					 }
					 if (!belongAsset.contains(spaceAssetEntity.getBelongAsset())){
						 errorLines++;
						 errorMessage.add("空间资产，第 " + (i+4) + " 行，所属资产填写有误，忽略导入。");
						 continue;
					 }
					 if (StringUtils.isBlank(spaceAssetEntity.getCompany())){
						 errorLines++;
						 errorMessage.add("空间资产，第 " + (i+4) + " 行，所属公司不能为空，忽略导入。");
						 continue;
					 }
					 if (!assetCompany.contains(spaceAssetEntity.getCompany())){
						 errorLines++;
						 errorMessage.add("空间资产，第 " + (i+4) + " 行，所属公司填写有误，忽略导入。");
						 continue;
					 }
					 if (StringUtils.isBlank(spaceAssetEntity.getAssetType())){
						 errorLines++;
						 errorMessage.add("空间资产，第 " + (i+4) + " 行，资产类型不能为空，忽略导入。");
						 continue;
					 }
					 if (spaceAssetEntity.getCompletionYear() == null){
						 errorLines++;
						 errorMessage.add("空间资产，第 " + (i+4) + " 行，建成日期不能为空，忽略导入。");
						 continue;
					 }
					 if (!assetAllCode.contains(spaceAssetEntity.getAssetType())){
						 errorLines++;
						 errorMessage.add("空间资产，第 " + (i+4) + " 行，资产类型填写有误，忽略导入。");
						 continue;
					 }
					 AssetMessage assetMessage = new AssetMessage();
					 BeanUtils.copyProperties(spaceAssetEntity, assetMessage);
					 assetMessage.setType("1");
					 String assetCode = getAssetCode(assetMessage);
					 assetMessage.setAssetCode(assetCode);
					 try {
						 successLines++ ;
						 assetMessageService.save(assetMessage);
					 } catch (Exception e) {
						 errorLines++;
						 errorMessage.add("空间资产，第 " + (i+4) + " 行，"+ e.getMessage() +"，忽略导入。");
					 }
				 }
				 // 如果需要基于对象的所有属性进行比较去重
				 Set<SpaceAssetEntity> spaceAssetSet = new HashSet<>(list1);
				 list2.removeIf(equipmentAsset -> {
					 SpaceAssetEntity temp = new SpaceAssetEntity();
					 BeanUtils.copyProperties(equipmentAsset, temp);
					 return spaceAssetSet.contains(temp);
				 });
				 list2 = list2.subList(list1.size(), list2.size());
				 for (int i = 0; i < list2.size(); i++) {
					 EquipmentAssetEntity equipmentAssetEntity = list2.get(i);
					 if (StringUtils.isBlank(equipmentAssetEntity.getAssetName())){
						 equiErrorLines++;
						 errorMessage.add("设备资产，第 " + (i+4) + " 行，资产名称不能为空，忽略导入。");
					 }
					 if (StringUtils.isBlank(equipmentAssetEntity.getBelongAsset())){
						 equiErrorLines++;
						 errorMessage.add("设备资产，第 " + (i+4) + " 行，所属资产不能为空，忽略导入。");
						 continue;
					 }
					 if (!belongAsset.contains(equipmentAssetEntity.getBelongAsset())){
						 errorLines++;
						 errorMessage.add("设备资产，第 " + (i+4) + " 行，所属资产填写有误，忽略导入。");
						 continue;
					 }
					 if (StringUtils.isBlank(equipmentAssetEntity.getCompany())){
						 equiErrorLines++;
						 errorMessage.add("设备资产，第 " + (i+4) + " 行，所属公司不能为空，忽略导入。");
						 continue;
					 }
					 if (!assetCompany.contains(equipmentAssetEntity.getCompany())){
						 errorLines++;
						 errorMessage.add("设备资产，第 " + (i+4) + " 行，所属公司填写有误，忽略导入。");
						 continue;
					 }
					 if (StringUtils.isBlank(equipmentAssetEntity.getBelongSpaceCode())){
						 equiErrorLines++;
						 errorMessage.add("设备资产，第 " + (i+4) + " 行，所属空间不能为空，忽略导入。");
						 continue;
					 }
					 if (StringUtils.isBlank(equipmentAssetEntity.getAssetType())){
						 errorLines++;
						 errorMessage.add("设备资产，第 " + (i+4) + " 行，资产类型不能为空，忽略导入。");
						 continue;
					 }
					 if (equipmentAssetEntity.getPurchaseDate() == null){
						 equiErrorLines++;
						 errorMessage.add("设备资产，第 " + (i+4) + " 行，采购日期不能为空，忽略导入。");
						 continue;
					 }
					 if (!assetAllCode.contains(equipmentAssetEntity.getAssetType())){
						 errorLines++;
						 errorMessage.add("设备资产，第 " + (i+4) + " 行，资产类型填写有误，忽略导入。");
						 continue;
					 }
					 AssetMessage assetMessage = new AssetMessage();
					 BeanUtils.copyProperties(equipmentAssetEntity, assetMessage);
					 assetMessage.setType("2");
					 String assetCode = getAssetCode(assetMessage);
					 assetMessage.setAssetCode(assetCode);
					 try {
						 equiSuccessLines++ ;
						 assetMessageService.save(assetMessage);
					 } catch (Exception e) {
						 equiErrorLines++;
						 errorMessage.add("设备资产，第 " + (i+4) + " 行，"+ e.getMessage() +"，忽略导入。");
					 }
				 }
				 return ImportExcelUtil.imporReturnRes2(errorLines,successLines,equiSuccessLines,equiErrorLines,errorMessage);
			 } catch (Exception e) {
				 log.error(e.getMessage(),e);
				 return Result.error("文件导入失败:"+e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (Exception e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
	 }

	/** 获取资产编码**/
	private String getAssetCode(AssetMessage assetMessage){
		// 资产编码前缀
		String code = assetMessage.getAssetType();
		// 生成的资产编码
		String assetCode = "";
		// 年份
		String year = "";
		SimpleDateFormat format = new SimpleDateFormat("yyyy");
		if ("1".equals(assetMessage.getType())){
			year = format.format(assetMessage.getCompletionYear());
		}else{
			year = format.format(assetMessage.getPurchaseDate());
		}
		// 所属资产
//		String belongAsset = sysDictService.queryDictTextByKey("asset_type", assetMessage.getBelongAsset());
		code = code + "-" + assetMessage.getBelongAsset();
		// 所属公司
//		String company = sysDictService.queryDictTextByKey("asset_company", assetMessage.getCompany());
		code = code + "-" + assetMessage.getCompany() + "-" + year + "-";
		int count = assetMessageService.getCount(code);
		// count+1,小于4位的话，格式化为四位数
		if (count <= 9998){
			assetCode = code + String.format("%04d", count+1);
		}else{
			assetCode = code + String.valueOf(count+1);
		}
		return assetCode;
	}



	 @PostMapping(value = "/changeVisible")
	 @Transactional
	 public Result<String> changeVisible(@RequestBody AssetMessage assetMessage) {
		 UpdateWrapper<AssetMessage> updateWrapper = new UpdateWrapper<>();
		 updateWrapper.set("is_visible", assetMessage.getIsVisible());
		 updateWrapper.eq("id", assetMessage.getId());
		 assetMessageService.update(updateWrapper);
		 AssetMessageChange assetMessageChange = new AssetMessageChange();
		 assetMessageChange.setChangeField("is_visible");
		 assetMessageChange.setChangeFieldName("可见性");
		 assetMessageChange.setOldValue(assetMessage.getIsVisible().equals("1") ? "不可见" : "可见");
		 assetMessageChange.setNewValue(assetMessage.getIsVisible().equals("1") ? "可见" : "不可见");
		 assetMessageChange.setPid(assetMessage.getId());
		 assetMessageChangeService.save(assetMessageChange);
		 return Result.OK("修改成功！");
	 }

	 /**
	  * 四张卡片统计
	  */
	 @ApiOperation(value="资产台账-四张卡片统计", notes="资产台账-四张卡片统计")
	 @GetMapping(value = "/cardTotal")
	 public Result<Map<String, Object>> cardTotal() {
		 Map<String, Object> map = new HashMap<>();
		 QueryWrapper<AssetMessage> queryWrapper = new QueryWrapper<>();
		 // 空间资产数量
		 List<AssetMessage> spaceAssetList = assetMessageService.list(queryWrapper.eq("type", 1));
		 map.put("spaceAssetTotal", spaceAssetList.size());
		 // 设备资产数量
		 queryWrapper.clear();
		 List<AssetMessage> equipAssetList = assetMessageService.list(queryWrapper.eq("type", 2));
		 map.put("equipAssetTotal", equipAssetList.size());
		 // 空间使用率 获取 status为1（运营状态），floorArea求和
		 double usedFloorArea = spaceAssetList.stream()
				 .filter(asset -> asset.getBuildingArea() != null && asset.getStatus().equals("1"))
				 .mapToDouble(asset -> Double.parseDouble(asset.getBuildingArea().toString()))
				 .sum();
		 double allFloorArea = spaceAssetList.stream()
				 .filter(asset -> asset.getBuildingArea() != null)
				 .mapToDouble(asset -> Double.parseDouble(asset.getBuildingArea().toString()))
				 .sum();
		 if (allFloorArea != 0){
			 //百分比 保留两位小数
			 map.put("spaceUseRate", new DecimalFormat("0.00").format(usedFloorArea / allFloorArea * 100));
		 }else {
			 map.put("spaceUseRate", 0);
		 }

		 // 设备使用率
		 // 空间使用率 获取 status为1（运营状态），floorArea求和
		 double usedEquipSize = equipAssetList.stream()
				 .filter(asset -> ("1").equals(asset.getStatus())).collect(Collectors.toList()).size();
		 if (equipAssetList.size() != 0){
			 //百分比 保留两位小数
			 map.put("equipGoodRate", new DecimalFormat("0.00").format(usedEquipSize * 100 / equipAssetList.size()));
		 }else {
			 map.put("equipGoodRate", 0);
		 }
		 return Result.OK(map);
	 }


}
